import {query, remove, saveOrUpdate} from './service';

export default {
  namespace: 'businessUser',

  state: {
    data: {},
    loading: true,
    pagination: {},
    searchWhere: {},
  },

  effects: {
    *fetch({ payload }, { select, call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const businessUser = yield select(state => state.businessUser);
      if (!payload) {
        payload = {};
      }
      payload = businessUser.searchWhere;
      //对象的合并 Object.assign(payload, pagination)----->Object.assign(目标对象, 被合并的对象) 如果目标对象与被合并对象有相同的属性变量，目标对象中属性值会被覆盖
      Object.assign(payload, businessUser.pagination);
      const response = yield call(query, payload);
      if(response.resultCode==="1") {
        yield put({
          type: 'save',
          payload: response,
        });
        yield put({
          type: 'changeLoading',
          payload: false,
        });
      }
    },

    *add({ payload, callback }, { call, put }) {
      const response = yield call(saveOrUpdate, payload);
      if(response.resultCode==="1") {
        yield put({ type: 'fetch' })
      }
      if (callback) callback(response);
    },
    *edit({ payload, callback }, { call, put }) {
      const response = yield call(saveOrUpdate, payload);
      if(response.resultCode==="1") {
        yield put({ type: 'fetch' })
      }
      if (callback) callback(response);
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(remove, payload);
      if(response.resultCode==="1"){
        yield put({ type: 'fetch' })
      }
      if (callback) callback(response);
    }
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
  },
};
